package com.schpro.webexperiment.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import java.io.IOException;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO
 *
 * @author lss
 * @date 2019-02-27, Wed
 */
public class JsonUtil {

  /**
   * 日志打印
   */
  private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

  /**
   * json mapper
   */
  private static ObjectMapper mapper = new ObjectMapper();

  static {
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  }

  /**
   * 转换对象为JSON String
   *
   * @param object json对象
   * @return 字符串
   */
  public static String toJsonString(Object object) {
    if (object == null) {
      return null;
    }
    try {
      return mapper.writeValueAsString(object);
    } catch (JsonProcessingException e) {
      logger.error("", e);
    }
    return "";
  }

  /**
   * 转换字符串为对象
   *
   * @param json  json字符串
   * @param clazz 对象class
   * @return obj
   */
  public static <T> T readValue(String json, Class<T> clazz) {
    if (Strings.isNullOrEmpty(json)) {
      return null;
    }
    try {
      return mapper.readValue(json, clazz);
    } catch (IOException e) {
      logger.error("", e);
      return null;
    }
  }

  /**
   * 将字符串转换成Map
   *
   * @param json 要转换的字符串
   * @return Map
   */
  public static Map<String, Object> convertToMap(String json) {
    Map<String, Object> map;
    try {
      map = JsonUtil.mapper.readValue(json, new TypeReference<Map<String, Object>>() {
      });
    } catch (IOException e) {
      logger.error("parse json error");
      return null;
    }
    return map;
  }
}

